<?php


namespace Agoni\DaDa;
use GuzzleHttp;
use Agoni\DispatchException;
use Agoni\Api;
class ApiRequest implements Api
{
    /**
     * @var string
     */
    private $appKey;

    /**
     * @var string
     */
    private $secret;
    private $source_id;
    private $api = 'https://newopen.qa.imdada.cn';

    private $header=['contentType'=>"application/json"];
    public function __construct(string $appKey, string $secret,string $source_id)
    {
        $this->appKey = $appKey;
        $this->secret = $secret;
        $this->source_id=$source_id;
    }

    /**
     * @param string $method
     * @param array $params
     * @return mixed
     * @throws DispatchException
     */
    public function request($url, array $params=[],$method="post")
    {
        $body=json_encode($params);

        $params = [
            'app_key' => $this->appKey,
            'source_id'=>$this->source_id,
            'timestamp' => time(),
            'v' => "1.0",
            'format'=>'json',
            'body'=>$body
        ];

        $params['signature'] = $this->signature($params);

        $client=new GuzzleHttp\Client();

        $data['json']=$params;

        $res=$client->request($method,$this->api.$url,$data);
        $results=$res->getBody()->getContents();
        print_r(json_decode($results,true));die;
//        print_r($params);die;
//
//        $http = $this->getHttp();
//
//        $response = $http->post(self::URL . $method, $params);
//
//        $result = json_decode(strval($response->getBody()), true);
//
//        $this->checkErrorAndThrow($result);

        return $result;
    }

    public function signature(array $params)
    {
        ksort($params);
//        if(empty($this->SOURCE_ID)){
//            unset($params['source_id']);
//        }

        $waitSign = '';
        foreach ($params as $key => $item) {
            if ($item) {
                $waitSign .= $key.$item;
            }
        }

        $str = $this->secret.$waitSign.$this->secret;

        $signature = md5($str);
        return strtoupper($signature);

        //return strtolower(sha1($this->secret.$waitSign));
    }

    /**
     * @param $result
     * @throws DispatchException
     */
    public function checkErrorAndThrow($result)
    {
        if (!$result || $result['code'] != 0) {
            throw new DispatchException($result['message'], $result['code']);
        }
    }
}